package tool;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

import java.io.Serializable;
import javax.xml.bind.JAXBException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.stream.XMLStreamException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.xml.sax.SAXException;
import com.sun.codemodel.JCodeModel;
import com.sun.tools.xjc.api.ErrorListener;
import com.sun.tools.xjc.api.S2JJAXBModel;
import com.sun.tools.xjc.api.SchemaCompiler;
import com.sun.tools.xjc.api.XJC;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamReader;
import org.xml.sax.InputSource;
import org.xml.sax.SAXParseException;
import org.xml.sax.helpers.DefaultHandler;

/**
 *
 * @author Vinh Nguyen
 */
public class XMLTools implements Serializable {

    public static void XJCGenerateJavaObj(String output, String packageName, String fileSchemaPath) throws IOException {
        SchemaCompiler sc = XJC.createSchemaCompiler();
        sc.setErrorListener(new ErrorListener() {

            public void error(SAXParseException saxpe) {
                System.out.println("Error" + saxpe.getMessage());
            }

            public void fatalError(SAXParseException saxpe) {
                System.out.println("Error" + saxpe.getMessage());
            }

            public void warning(SAXParseException saxpe) {
                System.out.println("Warning" + saxpe.getMessage());
            }

            public void info(SAXParseException saxpe) {
                System.out.println("Info" + saxpe.getMessage());
            }
        });
        sc.forcePackageName(packageName);
        File schema = new File(fileSchemaPath);
        InputSource is = new InputSource(schema.toURI().toString());
        sc.parseSchema(is);
        S2JJAXBModel model = sc.bind();
        JCodeModel code = model.generateCode(null, null);
        code.build(new File(output));
    }

    public static Object JAXBIUnmarshalling(Object obj, String fileXMLPath) throws JAXBException {
        JAXBContext jc = JAXBContext.newInstance(obj.getClass());
        Unmarshaller u = jc.createUnmarshaller();
        File f = new File(fileXMLPath);
        obj = (Object) u.unmarshal(f);

        return obj;
    }

    public static void JAXBMarshalling(Object obj, String fileXMLPath) throws JAXBException {
        JAXBContext jc = JAXBContext.newInstance(obj.getClass());
        Marshaller m = jc.createMarshaller();
        m.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
        m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
        m.marshal(obj, new File(fileXMLPath));
    }

    public static Document parseXMLFiletoDOM(String fileXMLPath) throws ParserConfigurationException, SAXException, IOException {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();

        File file = new File(fileXMLPath);
        Document doc = db.parse(file);

        return doc;
    }

    public static XPath createXpathObj() {
        XPathFactory xpf = XPathFactory.newInstance();
        XPath xpath = xpf.newXPath();

        return xpath;

    }

    public static void writeDOMtoFile(Node node, String filePath) throws TransformerConfigurationException, TransformerException {
        TransformerFactory tff = TransformerFactory.newInstance();
        Transformer trans = tff.newTransformer();
        Source src = new DOMSource(node);
        File f = new File(filePath);
        Result result = new StreamResult(f);
        trans.setOutputProperty(OutputKeys.INDENT, "yes");
        trans.transform(src, result);
    }

    public static void parseFileToSax(String filePath, DefaultHandler saxObj) throws ParserConfigurationException, SAXException, IOException {
        SAXParserFactory spf = SAXParserFactory.newInstance();
        SAXParser sax = spf.newSAXParser();
        File f = new File(filePath);
        sax.parse(f, saxObj);
    }

    public static XMLStreamReader parseFileToStAXCursor(InputStream is) throws XMLStreamException
    {
        XMLInputFactory xif =  XMLInputFactory.newInstance();
        XMLStreamReader xsr = xif.createXMLStreamReader(is);

        return xsr;
    }

    public static String getTextOfStAXCursor(String tagName, XMLStreamReader xsr) throws XMLStreamException {
        String result = "";
        while (!xsr.getLocalName().equals(tagName)) {
            xsr.nextTag();
            xsr.next();
            result = xsr.getText().trim();
            xsr.nextTag();
        }

        return result;
    }
}
